<template>
  <div class="word-forum" :class="theme">
    <div class="admin-container">
      <!-- 顶部导航栏 -->
      <header class="admin-header">
        <div class="header-left">
          <h1>例句管理</h1>
          <div class="word-info" v-if="currentWord">
            <span class="word-text">{{ currentWord.word }}</span>
            <span class="word-meaning">{{ currentWord.meaning }}</span>
          </div>
        </div>
        <div class="header-right">
          <button class="theme-toggle" @click="toggleTheme">
            <span v-if="theme === 'light'">🌙</span>
            <span v-else>☀️</span>
          </button>
          <span class="admin-name">管理员</span>
        </div>
      </header>

      <!-- 主要内容区 -->
      <div class="admin-content">
        <!-- 搜索和筛选区域 -->
        <div class="toolbar">
          <div class="search-box">
            <input type="text" v-model="searchQuery" placeholder="搜索例句内容..." @input="applyFilters" />
            <button class="search-btn">
              <svg viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor"
                  d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 0 0 1.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 0 0-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 0 0 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" />
              </svg>
            </button>
          </div>

          <div class="word-selector">
            <select v-model="selectedWordId" @change="fetchSentences">
              <option value="">选择单词...</option>
              <option v-for="word in words" :key="word.id" :value="word.id">
                {{ word.word }} - {{ word.meaning }}
              </option>
            </select>
          </div>

          <button class="add-btn" @click="showAddModal = true">
            <svg viewBox="0 0 24 24" width="18" height="18">
              <path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
            </svg>
            添加例句
          </button>

          <button class="refresh-btn" @click="resetFilters">
            <svg viewBox="0 0 24 24" width="18" height="18">
              <path fill="currentColor"
                d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
            </svg>
            重置
          </button>
        </div>

        <!-- 例句表格 -->
        <div class="table-container">
          <table class="sentences-table">
            <thead>
              <tr>
                <th width="50">ID</th>
                <th>例句内容</th>
                <th>翻译</th>
                <th width="120">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="sentence in paginatedSentences" :key="sentence.id">
                <td>{{ sentence.id }}</td>
                <td class="sentence-cell">
                  <div class="sentence-text">{{ sentence.sentence }}</div>
                </td>
                <td class="translation-cell">
                  <div class="translation-text">{{ sentence.translation || '暂无翻译' }}</div>
                </td>
                <td class="actions">
                  <button class="edit-btn" @click="editSentence(sentence)">
                    <svg viewBox="0 0 24 24" width="16" height="16">
                      <path fill="currentColor"
                        d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" />
                    </svg>
                  </button>
                  <button class="delete-btn" @click="confirmDelete(sentence)">
                    <svg viewBox="0 0 24 24" width="16" height="16">
                      <path fill="currentColor"
                        d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />
                    </svg>
                  </button>
                </td>
              </tr>
              <tr v-if="filteredSentences.length === 0">
                <td colspan="4" class="no-data">
                  {{ selectedWordId ? '没有找到匹配的例句' : '请先选择单词' }}
                </td>
              </tr>
            </tbody>
          </table>

          <!-- 分页控件 -->
          <div class="pagination" v-if="totalPages > 1">
            <button :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
              上一页
            </button>
            <span v-for="page in visiblePages" :key="page" @click="changePage(page)"
              :class="{ active: page === currentPage }">
              {{ page }}
            </span>
            <button :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">
              下一页
            </button>
            <span class="page-info">共 {{ filteredSentences.length }} 条，每页 {{ pageSize }} 条</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑例句模态框 -->
    <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ isEditing ? '编辑例句' : '添加例句' }}</h2>
          <button class="close-btn" @click="showAddModal = false">
            <svg viewBox="0 0 24 24" width="20" height="20">
              <path fill="currentColor"
                d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="sentence">例句内容</label>
            <textarea id="sentence" v-model="currentSentence.sentence" placeholder="输入例句内容..." rows="3"></textarea>
          </div>
          <div class="form-group">
            <label for="translation">翻译</label>
            <textarea id="translation" v-model="currentSentence.translation" placeholder="输入翻译内容..."
              rows="3"></textarea>
          </div>
          <div class="form-group" v-if="!isEditing">
            <label>关联单词</label>
            <select v-model="currentSentence.word_id">
              <option v-for="word in words" :key="word.id" :value="word.id">
                {{ word.word }} - {{ word.meaning }}
              </option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showAddModal = false;">
            取消
          </button>
          <button class="confirm-btn" @click="saveSentence">
            {{ isEditing ? '保存更改' : '添加例句' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="confirm-modal">
        <div class="confirm-header">
          <h3>确认删除</h3>
        </div>
        <div class="confirm-body">
          <p>确定要删除这个例句吗？此操作无法撤销。</p>
          <div class="sentence-preview">
            <p>"{{ sentenceToDelete.sentence }}"</p>
            <p v-if="sentenceToDelete.translation">翻译: {{ sentenceToDelete.translation }}</p>
          </div>
        </div>
        <div class="confirm-footer">
          <button class="cancel-btn" @click="showDeleteConfirm = false">
            取消
          </button>
          <button class="confirm-btn" @click="deleteSentence">
            确认删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getWordsData, getSentencesDataAPI, deleteWordSentenceByIdApi, addWordSentenceApi, updateWordSentenceByIdApi } from '../../api/authService.js';
// 主题功能
const theme = inject("theme", ref('light'));
const toggleTheme = () => {
  theme.value = theme.value === 'light' ? 'dark' : 'light';
};

// 分页设置
const pageSize = ref(5);
const currentPage = ref(1);

// 数据状态
const words = ref([
  { id: 1, word: 'example', meaning: '例子' }
]);

const sentences = ref([
  { id: 1, word_id: 1, sentence: 'This is an example sentence.', translation: '这是一个例句。' }
]);

// 筛选和搜索
const selectedWordId = ref('');
const searchQuery = ref('');
const currentWord = computed(() => words.value.find(word => word.id === parseInt(selectedWordId.value)));

// 模态框状态
const showAddModal = ref(false);
const showDeleteConfirm = ref(false);
const isEditing = ref(false);
const currentSentence = ref({ id: null, word_id: null, sentence: '', translation: '' });
const sentenceToDelete = ref(null);

// 计算属性
const filteredSentences = computed(() => {
  let result = sentences.value;

  // 按单词筛选
  if (selectedWordId.value) {
    result = result.filter(s => s.word_id === parseInt(selectedWordId.value));
  }

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(s =>
      s.sentence.toLowerCase().includes(query) ||
      (s.translation && s.translation.toLowerCase().includes(query))
    );
  }

  return result;
});

const totalPages = computed(() => Math.ceil(filteredSentences.value.length / pageSize.value));
const paginatedSentences = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredSentences.value.slice(start, end);
});

const visiblePages = computed(() => {
  const pages = [];
  const maxVisible = 5;
  let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2));
  let end = Math.min(totalPages.value, start + maxVisible - 1);

  if (end - start + 1 < maxVisible) {
    start = Math.max(1, end - maxVisible + 1);
  }

  for (let i = start; i <= end; i++) {
    pages.push(i);
  }

  return pages;
});

// 方法
const fetchSentences = () => {
  currentPage.value = 1;
};

const applyFilters = () => {
  currentPage.value = 1;
};

const resetFilters = () => {
  selectedWordId.value = '';
  searchQuery.value = '';
  currentPage.value = 1;
};

const changePage = (page) => {
  currentPage.value = page;
};

const editSentence = (sentence) => {
  currentSentence.value = { ...sentence };
  isEditing.value = true;
  showAddModal.value = true;
};

const saveSentence = () => {
  if (!currentSentence.value.sentence.trim()) {
    alert('例句内容不能为空');
    return;
  }

  if (isEditing.value) {
    // 更新例句
    const index = sentences.value.findIndex(s => s.id === currentSentence.value.id);

    const newSentenceData = {
      id: currentSentence.value.id,
      // word_id: currentSentence.value.word_id,
      sentence: currentSentence.value.sentence,
      translation: currentSentence.value.translation
    }
    // console.log();
    updateWordSentenceById(newSentenceData)
    if (index !== -1) {
      sentences.value[index] = { ...currentSentence.value };
    }
  } else {
    // 添加新例句
    if (!currentSentence.value.word_id) {
      alert('请选择关联单词');
      return;
    }

    const newId = Math.max(...sentences.value.map(s => s.id), 0) + 1;
    const newSentenceData = {
      word_id: currentSentence.value.word_id,
      sentence: currentSentence.value.sentence,
      translation: currentSentence.value.translation
    }
    addWordSentence(newSentenceData);
    sentences.value.push({
      id: newId,
      word_id: currentSentence.value.word_id,
      sentence: currentSentence.value.sentence,
      translation: currentSentence.value.translation
    });
    // console.log(newSentenceData);

  }
  showAddModal.value = false;
  resetCurrentSentence();
};
const updateWordSentenceById = async (Sdata) => {
  // console.log(Sdata, "更新");
  try {
    const response = await updateWordSentenceByIdApi(Sdata.id,
      {
        sentence: Sdata.sentence,
        translation: Sdata.translation
      }
    );
    if (response) {
      console.log(response);
    } else {
      console.log("更新失败");
    }
  } catch (error) {
    console.log(error);
  }
}


const addWordSentence = async (Sdata) => {
  try {
    const response = await addWordSentenceApi(Sdata.word_id,
      {
        sentence: Sdata.sentence,
        translation: Sdata.translation
      }
    );
    if (response) {
      console.log(response);
    } else {
      console.log("添加失败");
    }
  } catch (error) {
    console.log(error);
  }
}

const resetCurrentSentence = () => {
  currentSentence.value = { id: null, word_id: selectedWordId.value || null, sentence: '', translation: '' };
  isEditing.value = false;
};

const confirmDelete = (sentence) => {
  sentenceToDelete.value = sentence;
  showDeleteConfirm.value = true;
};

const deleteSentence = () => {
  // console.log(sentenceToDelete.value.id);
  sentences.value = sentences.value.filter(s => s.id !== sentenceToDelete.value.id);
  deleteWordSentenceById(sentenceToDelete.value.id);
  showDeleteConfirm.value = false;
};

const deleteWordSentenceById = async (id) => {
  try {
    const response = await deleteWordSentenceByIdApi(id);
    if (response) {
      console.log('response', response);
    }
  } catch (error) {
    console.error('Error deleting sentence:', error);
  }
};

const getWordDataIN = async () => {
  try {
    const response = await getWordsData();
    if (response.data) {
      // console.log('response.data', response.data);
      // words.value = handWordData(response.data);
      // console.log('words', words.value);
      return response.data;
    } else {
      console.log('获取单词数据失败');
    }
  } catch (error) {
    console.log('获取单词数据失败', error);
  }
}
const handWordData = (wordData) => {
  const AfterData = wordData.map((item) => {
    return {
      id: item.id,
      word: item.word,
      meaning: item.definition
    };
  });
  return AfterData;
}
const getSentencesData = async () => {
  // console.log('getSentencesData');
  try {
    const response = await getSentencesDataAPI();
    // console.log('response', response);
    if (response.sentences) {
      // console.log('response.data', response.sentences);
      // sentences.value = response.sentences;
      return response.sentences;
    } else {
      console.log('获取句子数据失败');
    }
  } catch (error) {
    console.log('获取句子数据失败', error);
  }

}

const loadPageData = async () => {
  try {
    const [wordData, sentencesData] = await Promise.all([
      getWordDataIN(),
      getSentencesData()
    ])
    words.value = handWordData(wordData);
    sentences.value = sentencesData;
    resetCurrentSentence();

  } catch (error) {
    console.error(error)
    ElMessage.error('请求数据失败')
  }
}

// 初始化
onMounted(() => {
  // resetCurrentSentence();
  // getWordDataIN()
  loadPageData();

});
</script>

<style scoped>
.word-forum {
  --bg-color: #f8f9fa;
  --text-color: #333;
  --primary-color: #4361ee;
  --secondary-color: #6c757d;
  --border-color: #e1e4e8;
  --card-bg: #fff;
  --hover-bg: #f1f3f5;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  --danger-color: #dc3545;
  --warning-color: #ffc107;
  --success-color: #28a745;
  --info-color: #17a2b8;
}

.word-forum.dark {
  --bg-color: #1a1a1a;
  --text-color: #e0e0e0;
  --primary-color: #4895ef;
  --secondary-color: #8e8e8e;
  --border-color: #333;
  --card-bg: #2d2d2d;
  --hover-bg: #383838;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.admin-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 0 20px;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0;
  font-size: 24px;
  color: var(--primary-color);
}

.word-info {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.word-text {
  font-weight: bold;
  color: var(--primary-color);
}

.word-meaning {
  font-size: 14px;
  color: var(--secondary-color);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.theme-toggle {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: var(--text-color);
  padding: 5px;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.theme-toggle:hover {
  background-color: var(--hover-bg);
}

.admin-name {
  font-weight: 500;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  display: flex;
  align-items: center;
  flex-grow: 1;
  max-width: 400px;
}

.search-box input {
  flex-grow: 1;
  padding: 10px 15px;
  border: 1px solid var(--border-color);
  border-radius: 4px 0 0 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
}

.search-btn {
  padding: 10px 15px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn:hover {
  opacity: 0.9;
}

.word-selector select {
  padding: 10px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
  cursor: pointer;
  min-width: 200px;
}

.add-btn {
  padding: 10px 15px;
  background-color: var(--success-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.add-btn:hover {
  opacity: 0.9;
}

.refresh-btn {
  padding: 10px 15px;
  background-color: var(--secondary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.refresh-btn:hover {
  opacity: 0.9;
}

.table-container {
  background-color: var(--card-bg);
  border-radius: 8px;
  box-shadow: var(--shadow);
  overflow: hidden;
}

.sentences-table {
  width: 100%;
  border-collapse: collapse;
}

.sentences-table th,
.sentences-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.sentences-table th {
  background-color: var(--hover-bg);
  font-weight: 600;
}

.sentences-table tr:hover {
  background-color: var(--hover-bg);
}

.sentence-cell,
.translation-cell {
  max-width: 400px;
}

.sentence-text,
.translation-text {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
}

.translation-text {
  color: var(--secondary-color);
  font-style: italic;
}

.actions {
  display: flex;
  gap: 8px;
}

.edit-btn,
.delete-btn {
  padding: 6px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
}

.edit-btn {
  color: var(--warning-color);
}

.edit-btn:hover {
  background-color: rgba(255, 193, 7, 0.1);
}

.delete-btn {
  color: var(--danger-color);
}

.delete-btn:hover {
  background-color: rgba(220, 53, 69, 0.1);
}

.no-data {
  text-align: center;
  padding: 20px;
  color: var(--secondary-color);
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  gap: 10px;
  align-items: center;
}

.pagination button,
.pagination span {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  background-color: var(--card-bg);
  color: var(--text-color);
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination span.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.page-info {
  margin-left: 15px;
  font-size: 14px;
  color: var(--secondary-color);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--card-bg);
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: var(--shadow);
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--secondary-color);
  padding: 5px;
}

.close-btn:hover {
  color: var(--text-color);
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group textarea,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: var(--secondary-color);
  color: white;
  border: none;
}

.confirm-btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
}

.confirm-btn:hover {
  opacity: 0.9;
}

.confirm-modal {
  background-color: var(--card-bg);
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: var(--shadow);
}

.confirm-header {
  padding: 15px 20px;
  border-bottom: 1px solid var(--border-color);
}

.confirm-header h3 {
  margin: 0;
  font-size: 18px;
}

.confirm-body {
  padding: 20px;
}

.sentence-preview {
  margin-top: 15px;
  padding: 15px;
  background-color: var(--hover-bg);
  border-radius: 4px;
}

.sentence-preview p {
  margin: 5px 0;
}

.confirm-footer {
  padding: 15px 20px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    max-width: 100%;
  }

  .word-selector select {
    width: 100%;
  }

  .sentences-table {
    display: block;
    overflow-x: auto;
  }

  .modal-body {
    padding: 15px;
  }

  .form-group {
    margin-bottom: 15px;
  }
}
</style>